package com.example.config.shiro;

import com.example.constant.shiro.CommonProperties;
import com.example.util.shiro.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @application:
 * @author: LiYuhang
 * @Date: 2021/7/26 11:48
 * @version: 0.1
 * @Description :
 * @Modified By:
 */

/**
 * used by HashedCredentialsMatcher
 */
@Component
@Deprecated
public class CredentialsMatcher extends SimpleCredentialsMatcher {
    private static final Logger LOGGER = LoggerFactory.getLogger(CredentialsMatcher.class);

    @Resource
    private RedisUtil redisCacheService;

    @Override
    public boolean doCredentialsMatch(AuthenticationToken authenticationToken,AuthenticationInfo info) {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName = token.getUsername();
        //表示JWT访问时，直接跳过
        if ("jwt".equals(userName)) {
            return true;
        }
        redisCacheService.incr(CommonProperties.LOGIN_COUNT + userName, 1);
        String errorCount = redisCacheService.getString(CommonProperties.LOGIN_COUNT + userName);
        String accountState = redisCacheService.getString(userName + CommonProperties.LOCK_KEY);
        int count = 0;
        if (StringUtils.isNumeric(errorCount)) {
            count = Integer.parseInt(errorCount);
        }
        /** 计数大于5时，设置用户被锁定一小时*/
        if (count > CommonProperties.PASSWORD_ERROR_TIMES) {
            redisCacheService.set(userName + CommonProperties.LOCK_KEY, CommonProperties.LOCK_VALUE);
            redisCacheService.expire(userName + CommonProperties.LOCK_KEY, 1);
            redisCacheService.del(CommonProperties.LOGIN_COUNT + userName);
        }
        /** 判断账户是否被锁定*/
        if (CommonProperties.LOCK_VALUE.equals(accountState)) {
            LOGGER.info("由于你连续输错5次，当前页面被锁定！");
            throw new LockedAccountException("由于你连续输错5次，当前账户被锁定1小时！");
        }
        /** 获得用户输入的密码*/
        String password1 = new String(token.getPassword());
        /** 获得数据库中的密码*/
        String password2 = (String) info.getCredentials();
        LOGGER.info("用户输入的密码[{}]--equals--数据库的密码[{}]", password1, password2);
        if (this.equals(password1, password2)) {
            redisCacheService.del(CommonProperties.LOGIN_COUNT + userName);
            return true;
        } else {
            return false;
        }
    }
}
